package com.dashu.device.service.CQ;


import com.dashu.base.utils.CopyUtil;
import com.dashu.base.utils.ToEntityAnStr;
import com.dashu.device.api.CQ.CQInsideServerApi;
import com.dashu.device.bean.CQ.CQBaseResp;
import com.dashu.device.bean.CQ.CQRegBean;
import com.dashu.device.bean.CQ.CQResultBean;
import com.dashu.device.util.CQWriteUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


import static com.dashu.device.container.CQContainer.CQonlineObj;
import static com.dashu.device.container.CQContainer.CQonlineStr;
import static com.dashu.device.tools.CQMark.*;

@Slf4j
@Service
public class CQInsideInsideService<T> implements CQInsideServerApi<T> {
    /**
     * 设备注册
     */
    @Override
    public void register(ChannelHandlerContext ctx, CQBaseResp req) {
        CQRegBean regResp = new CQRegBean();
        regResp.setTimestamp(System.currentTimeMillis());
        regResp.setKeepAliveTime(10);
        CQBaseResp baseResp = CQWriteUtil.response(REGISTRESP, req, regResp);
        CQWriteUtil.send(ctx, ToEntityAnStr.obj2String(baseResp));
    }

    /**
     * 设备心跳
     */
    @Override
    public void heartbeat(ChannelHandlerContext ctx, Object object,long cacheTime) {
        CQBaseResp cqBaseResp = CopyUtil.copyEnty(object,CQBaseResp.class) ;
        CQBaseResp baseResp = CQWriteUtil.response(HEARTRESP, cqBaseResp, null);
        if (CQonlineStr.get(baseResp.getSn()) == null) {
            CQonlineStr.put(cqBaseResp.getSn(), ctx);
        }
        if (CQonlineObj.get(ctx) == null) {
            CQonlineObj.put(ctx, cqBaseResp.getSn());
            log.info("添加在线:" + cqBaseResp.getSn());
        }
        CQWriteUtil.send(ctx, ToEntityAnStr.obj2String(baseResp));
    }


    @Override
    public void compared(ChannelHandlerContext ctx, Object object, String msg) {
        log.info("" + ctx.channel().remoteAddress().toString() + "--compared");
        CQBaseResp cqBaseResp = CopyUtil.copyEnty(object,CQBaseResp.class) ;
        CQBaseResp comparedBaseResp = CQWriteUtil.response(COMPAREDRESP, cqBaseResp, new CQResultBean());
        CQWriteUtil.send(ctx, ToEntityAnStr.obj2String(comparedBaseResp));
    }


}
